package com.jamlu.framework.album;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by Lin on 2017/8/1.
 * 获取所有本地图片
 */

public class PickerManager {

//    private PickerManager mPickerManager;
    private Context mContext;
    //加载图片的标志
    public static final int LOAD_PHOTOS = 0xff7961;
    //获取本地图片成功
    public static final int IMG_SUCCESS = 0xff1653;
    //用于存储成功信息列表
    private List<Integer> mSuccessMsgs;
    //图片总表
    private List<ImageInfo> mAllImageImfos;
    //文件夹总表
    private List<FolderInfo> mAllFolderInfos;
    //更新本地图片
    private boolean mUpDataImgs = false;

    private ManagerCallBack mCallBack;

    public PickerManager(Context context) {
        this.mContext = context;
        mSuccessMsgs = new ArrayList<>();
        init();
    }

//    public static PickerManager getInstance(Context context) {
//        if (mPickerManager == null) {
//            mPickerManager = new PickerManager(context);
//        }
//        return mPickerManager;
//    }

    /**
     * 设置监听器
     *
     * @param callBack
     */

    public void setManagerCallBack(ManagerCallBack callBack) {
        this.mCallBack = callBack;
        if (mAllFolderInfos != null){
            mCallBack.callBack();
        }
    }

//    /**
//     * 获取所有图片的总表
//     *
//     * @return
//     */
//
//    public List<ImageInfo> getAllImageImfos() {
//        if (mSuccessMsgs != null && mSuccessMsgs.contains(IMG_SUCCESS) && mAllImageImfos != null) {
//            //排序操作
//            ImageInfo[] imageInfos = mAllImageImfos.toArray(new ImageInfo[mAllImageImfos.size()]);
//            ImageInfo tempInfo;
//            int size = imageInfos.length;
//            for (int i = 0; i < size - 1; i++) {
//                for (int j = 0; j < size - 1 - i; j++) {
//                    if (imageInfos[j].getLastModified() < imageInfos[j + 1].getLastModified())  //交换两数位置
//                    {
//                        tempInfo = imageInfos[j];
//                        imageInfos[j] = imageInfos[j + 1];
//                        imageInfos[j + 1] = tempInfo;
//                    }
//                }
//            }
//            List<ImageInfo> resultInfos = Arrays.asList(imageInfos);
//            return resultInfos;
//        }
//        return null;
//    }

    public List<FolderInfo> getAllFolderInfoList(){
        if (mAllFolderInfos == null) {
            mAllFolderInfos = new ArrayList<>();
        }
        return mAllFolderInfos;
    }

    /**
     * 获取所有文件夹总表
     *
     * @return
     */

    public List<FolderInfo> getAllFolderInThread() {
        if (mAllFolderInfos == null) {
            mAllFolderInfos = new ArrayList<>();
        }
        mAllFolderInfos.clear();
        Map<String, List<CameraInfo>> folderInfos = new HashMap<>();
        if (mAllImageImfos != null) {
            for (int i = 0; i < mAllImageImfos.size(); i++) {
                ImageInfo info = mAllImageImfos.get(i);
                if (folderInfos.containsKey(info.getFolder())) {
                    folderInfos.get(info.getFolder()).add(info);
                } else {
                    List<CameraInfo> infos = new ArrayList<>();
                    infos.add(info);
                    folderInfos.put(info.getFolder(), infos);
                }
            }
        }
        List<String> folderNames = new ArrayList<>();
        folderNames.addAll(folderInfos.keySet());
        for (int i = 0; i < folderNames.size(); i++) {
            FolderInfo info = new FolderInfo();
            info.setFolder(folderNames.get(i));
            List<CameraInfo> cameraInfos = folderInfos.get(folderNames.get(i));
            List<ImageInfo> imageInfos = new ArrayList<>();
            for (int y = 0; y < cameraInfos.size(); y++) {
                CameraInfo cameraInfo = cameraInfos.get(y);
//                if (cameraInfo instanceof ImageInfo) {
                    imageInfos.add((ImageInfo) cameraInfo); //肯定是它
//                }
            }
            info.setImageInfos(imageInfos);
            info.setSize(imageInfos.size());
            if (imageInfos.size() > 0) {
                info.setPath(imageInfos.get(0).getPath());
                info.setLastModified(imageInfos.get(0).getLastModified());
            }
            mAllFolderInfos.add(info);
        }
        if (mAllFolderInfos.size() > 0){
            Collections.sort(mAllFolderInfos, new Comparator<FolderInfo>() {
                @Override
                public int compare(FolderInfo o1, FolderInfo o2) {
                    return (o1.getLastModified() < o2.getLastModified() ? 1 :
                            (o1.getLastModified() == o2.getLastModified()  ? 0 : -1));
                }
            });
        }
        return mAllFolderInfos;
    }


    /**
     * 全更模式
     */

    public void setUpData() {
        setUpDataImgs(true);
    }

    /**
     * 设置是否重新更新图片列表(保存的时候)
     *
     * @param upDataImgs
     */

    private void setUpDataImgs(boolean upDataImgs) {
        this.mUpDataImgs = upDataImgs;
        if (mUpDataImgs) {
            //首先移除消息队列里成功信息
            if (mSuccessMsgs.contains(IMG_SUCCESS)) {
                for (int i = 0; i < mSuccessMsgs.size(); i++) {
                    if (mSuccessMsgs.get(i) == IMG_SUCCESS) {
                        mSuccessMsgs.remove(mSuccessMsgs.get(i));
                    }
                }
            }
            if (mAllImageImfos != null) {
                mAllImageImfos.clear();
            }
            if (mAllFolderInfos != null) {
                mAllFolderInfos.clear();
            }
            new Thread(new Runnable() {
                @Override
                public void run() {
                    ContentResolver contentResolver = mContext.getContentResolver();
                    if (contentResolver != null) {
                        Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                        loading(contentResolver, uri, LOAD_PHOTOS);
                    }
                }
            }).start();
        }
    }

    /**
     * 开启线程去加载本地数据
     */

    private void init() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (mContext != null) {
                    ContentResolver contentResolver = mContext.getContentResolver();
                    if (contentResolver != null) {
                        try {
                            //type one : load imgs
                            Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                            loading(contentResolver, uri, LOAD_PHOTOS);
                        } catch (Exception e) {
                            e.printStackTrace();
                            Log.d("PickerManager", "LOAD ERROR");
                        }
                    }
                }
            }
        }).start();
    }

    private void loading(ContentResolver contentResolver, Uri uri, int type) {
        Cursor cursor = contentResolver.query(uri, null, null, null, MediaStore.Images.Media.DATE_MODIFIED +" DESC");
        switch (type) {
            case LOAD_PHOTOS:
                if (cursor != null) {
                    mAllImageImfos = new ArrayList<>();
                    while (cursor.moveToNext()) {
                        //先获取图片的路径作为判断依据
                        String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                        if (path != null && new File(path).exists()) {
                            ImageInfo info = new ImageInfo();
                            info.setPath(path);
                            int id = cursor.getInt(cursor.getColumnIndex(MediaStore.Images.Media._ID));
                            info.setId(id);
                            String album = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.BUCKET_DISPLAY_NAME));
                            if (TextUtils.isEmpty(album) || album.equals("<unknown>")) {
                                //适配魅族辣鸡系统
                                String sdpath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;
                                String folder = path.substring(sdpath.length(), path.length());
                                if (folder.contains("/")) {
                                    album = folder.substring(0, folder.indexOf("/"));
                                } else {
                                    album = "Camera";
                                }
                            }
                            info.setFolder(album);
                            long fileSize = cursor.getLong(cursor.getColumnIndex(MediaStore.Images.Media.SIZE));
                            info.setSize(fileSize);
                            long lastModified = cursor.getLong(cursor.getColumnIndex(MediaStore.Images.Media.DATE_MODIFIED));
                            info.setLastModified(lastModified);
                            int rotation = cursor.getInt(cursor.getColumnIndex(MediaStore.Images.Media.ORIENTATION));
                            info.setRotation(rotation);
                            if (id == -1 || fileSize == -1 || path.endsWith(".gif")) {
                                continue;
                            }
                            mAllImageImfos.add(info);
                        }
                    }
                    cursor.close();
                    getAllFolderInThread();
                    //发送一个加载图片成功的信息
                    Message msg = mLoadingHandler.obtainMessage(IMG_SUCCESS);
                    mLoadingHandler.sendMessage(msg);
                }
                break;
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler mLoadingHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case IMG_SUCCESS:
                    //更新一次之后必须立马重置,否则会不断的重新更新的
                    mUpDataImgs = false;
                    if (mSuccessMsgs.contains(IMG_SUCCESS)) {
                        break;
                    }
                    mSuccessMsgs.add(IMG_SUCCESS);
                    Log.d("PickerManager", "LOAD IMG_SUCCESS");
                    if (mCallBack != null) {
                        mCallBack.callBack();
                    }
                    break;
            }
        }
    };

    public interface ManagerCallBack {
        void callBack();
    }

}
